<template>
  <div class="generate-container">
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <span class="logo">卡密管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <span class="user-info">
              <User class="user-icon" />
              <span>管理员</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu :default-openeds="['2']" router>
            <el-sub-menu index="1">
              <template #title>
                <DashboardIcon class="menu-icon" />
                <span>仪表盘</span>
              </template>
              <el-menu-item index="/dashboard">
                <span>数据统计</span>
              </el-menu-item>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <Key class="menu-icon" />
                <span>卡密管理</span>
              </template>
              <el-menu-item index="/generate">
                <span>生成卡密</span>
              </el-menu-item>
              <el-menu-item index="/keys">
                <span>卡密列表</span>
              </el-menu-item>
            </el-sub-menu>
          </el-menu>
        </el-aside>
        <el-main class="main-content">
          <el-card>
            <template #header>
              <div class="card-header">
                <span>生成卡密</span>
              </div>
            </template>
            <el-form ref="generateForm" class="generate-form">

              <el-form-item prop="count" :rules="rules.count">
                <el-input v-model="count" placeholder="请输入生成数量" :validate-event="false">
                  <template #suffix>
                    <span class="suffix-text">个</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="durationType" :rules="rules.durationType">
                <el-select v-model="durationType" placeholder="请选择卡密类型" style="width: 100%" :validate-event="false">
                  <el-option label="日卡" value="day"></el-option>
                  <el-option label="周卡" value="week"></el-option>
                  <el-option label="月卡" value="month"></el-option>
                  <el-option label="季卡" value="quarter"></el-option>
                  <el-option label="半年卡" value="half_year"></el-option>
                  <el-option label="年卡" value="year"></el-option>
                  <el-option label="永久卡" value="permanent"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleGenerate" style="width: 100%">生成卡密</el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card v-if="generatedKeys.length > 0" class="result-card">
            <template #header>
              <div class="card-header">
                <span>生成结果</span>
                <el-button type="primary" size="small" @click="copyToClipboard" class="copy-btn">
                  复制所有卡密
                </el-button>
              </div>
            </template>
            <div class="keys-container">
              <div v-for="key in generatedKeys" :key="key" class="key-item">{{ key }}</div>
            </div>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { User, DashboardIcon, Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()

const count = ref(1)
const durationType = ref('month')

const generatedKeys = ref([])
const rules = {

  count: [
    { required: true, message: '请输入生成数量', trigger: ['blur', 'change'] },
    { type: 'number', min: 1, max: 100, message: '生成数量必须在1-100之间', trigger: ['blur', 'change'] }
  ],
  durationType: [
    { required: true, message: '请选择卡密类型', trigger: ['blur', 'change'] }
  ]
}



// 生成卡密
const handleGenerate = async () => {
    try {
      // 从localStorage获取token
      const token = localStorage.getItem('token')
      if (!token) {
        router.push('/login')
        return
      }

      // 准备表单数据
      const formData = {
        count: Number(count.value),
        duration_type: durationType.value
      }

    // 调用后端API生成卡密
    const response = await axios.post('/api/generate', formData, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })

    if (response.data.success) {
      generatedKeys.value = response.data.data
      ElMessage.success(response.data.message || '生成成功')
    } else {
      ElMessage.error(response.data.message || '生成失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
    console.error('Failed to generate keys:', error)
  }
}

// 复制卡密到剪贴板
const copyToClipboard = () => {
  const text = generatedKeys.value.join('\n')
  navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('卡密已复制到剪贴板')
  }).catch(err => {
    ElMessage.error('复制失败，请手动复制')
    console.error('Failed to copy to clipboard:', err)
  })
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  ElMessage.success('退出成功')
  router.push('/login')
}

onMounted(() => {
  // 无需加载应用列表
})
</script>

<style scoped>
.generate-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.header {
  background-color: #409eff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}
.logo {
  font-size: 20px;
  font-weight: bold;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-icon {
  margin-right: 5px;
}
.sidebar {
  background-color: #f0f2f5;
  padding-top: 20px;
}
.menu-icon {
  margin-right: 10px;
}
.main-content {
  padding: 20px;
  background-color: #f5f7fa;
  overflow-y: auto;
  flex: 1;
}
.card-header {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.generate-form {
  padding: 20px;
}
.suffix-text {
  color: #909399;
}
.result-card {
  margin-top: 20px;
}
.keys-container {
  max-height: 400px;
  overflow-y: auto;
  background-color: #f0f2f5;
  padding: 10px;
  border-radius: 5px;
}
.key-item {
  padding: 5px 0;
  border-bottom: 1px solid #e4e7ed;
}
.key-item:last-child {
  border-bottom: none;
}
.copy-btn {
  margin-top: -5px;
}
</style>